// pages/components/uploader/uploader.js
import {ajax} from "../../../utils/httpRequest";
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    imgList: {
      type: Array,
      default: []
    },
    state:{
      type:Number
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    hidden: true
  },

  /**
   * 组件的方法列表
   */
  methods: {
    chooseImage: function (e) {
      var that = this;
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          let chooseList = res.tempFilePaths;
          for (let i = 0; i < chooseList.length; i++) {
            ajax.get('https://api.cloudcpc.com/home/Qiniu/upload',).then(
                res2 => {
                  that.comenUploadFun(res2.token, chooseList[i])
                }
            )
          }
          //console.log(res.tempFilePaths)
          // that.setData({
          //   files: that.data.files.concat(res.tempFilePaths)
          // });


        }
      })
    },
    comenUploadFun(token, path) {
      let that = this;
      wx.uploadFile({
        url: 'https://upload.qiniup.com',
        // url: 'https://up-z2.qiniup.com',
        filePath: path,
        name: 'file',
        header: {
          'Content-Type': 'multipart/form-data'
        },
        formData: {
          token: token
        },
        success: (res) => {
          var data = JSON.parse(res.data);
          var upladurl = 'http://oss.co-links.com/' + data.key;
          var tepArray = [];
          tepArray.push(upladurl);
          console.log(tepArray);
          // var upladurl = 'http://pjapi6s2a.bkt.clouddn.com/' + data.key;
          if (that.data.imgList.length < 9) {
            this.setData({
              imgList: that.data.imgList.concat(tepArray)
            });
          } else {
            wx.showToast({
              title: '最多上传9张图片',
              icon: 'none',
            });
          }
        },
        fail: (error) => {
          wx.showModal({
            title: "提示",
            content: '上传失败，请重试!',
            showCancel: false,
            confirmColor: '#0d77e4',
            success: function (res) {
              if (res.confirm) {

              }
            }
          })
        }
      })
    },
    previewImage: function (e) {
      // console.log(this.data.imgList);
      wx.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.data.imgList // 需要预览的图片http链接列表
      })
    },
    submitBtn(){
      this.triggerEvent('buttonclick', {
        imgList:this.data.imgList
      },{bubbles:true})
    },
  }
})
